import React, { useState, useEffect } from "react";
import dayjs from "dayjs";
import duration from "dayjs/plugin/duration";
import {
  getTimeMarkValueType,
  getTimeRangeTextInner,
} from "../../TimeRangePicker/utils";
import {
  DEFAULT_PRESET_ITEMS_DATA,
  DEFAULT_RELATIVE_ITEMS_DATA,
  DEFAULT_DURATION_UNIT_OPTIONS,
} from "../../TimeRangePicker/constant";
import classNames from "classnames";
import RelativeTime from "../../TimeRangePicker/components/RelativeTime";
import AbsoluteTime from "../../TimeRangePicker/components/AbsoluteTime";
import { useStyles } from "../../TimeRangePicker/style";
import {
  Timestamp,
  PresetValue,
  DurationUnitOption,
} from "../../TimeRangePicker/type";

dayjs.extend(duration);

export default TimeRangePickerFilter;

export { getLabel };

interface TimeRangeProps {
  value?: string; // iso string | 时间戳范围string, 例如"1656653541857/1657171941857"
  relativeItems?: string[]; //isoDurationString
  presetItems?: PresetValue[];
  onChange?: (value?: string) => void;
  durationUnitOptions?: DurationUnitOption[];
}

enum TabKey {
  RELATIVE = 0,
  ABSOLUTE = 1,
}

function TimeRangePickerFilter({
  value,
  onChange,
  relativeItems,
  presetItems,
  durationUnitOptions = DEFAULT_DURATION_UNIT_OPTIONS,
}: TimeRangeProps) {
  const classes = useStyles();
  const [timeMark, setTimeMark] = useState<string | undefined>();
  const [isReady, setIsReady] = useState<boolean>(false);
  const [activeKey, setActiveKey] = useState<TabKey>(TabKey.RELATIVE);
  const relativeTimeItems = {
    relativeItemsData: relativeItems || DEFAULT_RELATIVE_ITEMS_DATA,
    presetItemsData: presetItems || DEFAULT_PRESET_ITEMS_DATA,
  };

  const handleTabClick = (key: TabKey) => setActiveKey(key);

  const handleConfirm = (value: string, timestamp: Timestamp) => {
    setTimeMark(value);
    onChange && onChange(value);
  };

  useEffect(() => {
    if (value) {
      // 判断初始化数据是否为有效的字符串
      const initialValueType = getTimeMarkValueType(
        value,
        relativeTimeItems.presetItemsData
      );
      setActiveKey(
        initialValueType === "timeRange" ? TabKey.ABSOLUTE : TabKey.RELATIVE
      );
      setTimeMark(initialValueType ? value : undefined);
    } else {
      setTimeMark(undefined);
    }
    setIsReady(true);
  }, [value]);

  const tabContent = [
    {
      key: TabKey.RELATIVE,
      title: "相对时间",
      content: (
        <RelativeTime
          timeMark={timeMark}
          handleConfirm={handleConfirm}
          relativeItemsData={relativeTimeItems.relativeItemsData}
          presetItemsData={relativeTimeItems.presetItemsData}
          durationUnitOptions={durationUnitOptions}
        />
      ),
    },
    {
      key: TabKey.ABSOLUTE,
      title: "绝对时间",
      content: (
        <AbsoluteTime timeMark={timeMark} handleConfirm={handleConfirm} />
      ),
    },
  ];

  const activeContent = tabContent.find((t) => t.key === activeKey)?.content;

  if (isReady) {
    return (
      <div className={classes.customTab} role="overlay">
        <div className={classes.tabHead}>
          {tabContent.map((tab) => {
            return (
              <span
                className={classNames(
                  classes.tab,
                  activeKey === tab.key && classes.active
                )}
                onClick={() => handleTabClick(tab.key)}
                key={tab.key}
              >
                {tab.title}
              </span>
            );
          })}
        </div>
        <div className={classes.tabContent}>{activeContent}</div>
      </div>
    );
  }
  return <div />;
}

interface GetLabelProps
  extends Pick<TimeRangeProps, "value" | "relativeItems" | "presetItems"> {}
function getLabel({ value = undefined, presetItems }: GetLabelProps) {
  const presetItemsData = presetItems || DEFAULT_PRESET_ITEMS_DATA;
  if (value) {
    return getTimeRangeTextInner(value, presetItemsData);
  }
  return "";
}
